import axios from "axios";
import router from "@/router";

//创建一个新的axios对象
const request = axios.create({
    baseURL:process.env.VUE_APP_BASEURL,
    timeout:3000
})

//请求拦截器
//可以自请求发送前对请求做一些拦截的处理
request.interceptors.request.use(
    config =>{
        config.headers['content-Type'] = 'application/json;charset=uft-8'
        let user = localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) :null
        config.headers['token'] = user?.token
        return config
    },error=>{
        console.log('request error'+error)
        return Promise.reject(error)
    }
)

//response拦截器
//可以在接口响应后统一处理结果
request.interceptors.response.use(
    response=>{
        let res = response.data
        //兼容服务端返回的字符串数据
        if (typeof res === 'string'){
            res = res ? JSON.parse(res) : res
        }

        if (res.code==="401") router.push('/login')

        return res
    },error=>{
        console.error('response error'+error)
        return Promise.reject(error)
    }
)

export default request
